package com.djq.hhc.dataprocess;

import cn.hutool.core.lang.UUID;
import com.djq.hhc.result.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文件上传下载
 */
public class ImgLoadUtils {

    private static String basePath = "F:\\HHcommunity\\pic\\";
 
    /**
     * 文件上传
     * @param file
     * @return
     */
    public static String upLoad(MultipartFile file) {
 
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件类型（jpg、png）
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
 
        // 使用UUID重新生成文件名，防止文件名重复
        String fileName = UUID.randomUUID() + suffix;
 
        // 创建目录
        File dir = new File(basePath);
        if(!dir.exists()) {
            dir.mkdirs();
        }
 
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }
 
    /**
     * 文件下载
     * @param name
     * @param response
     */
    public static boolean downLoad(String name, HttpServletResponse response) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
 
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
 
            response.setContentType("image/jpeg");
 
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
 
            //关闭资源
            outputStream.close();
            fileInputStream.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}